<template>
  <el-row style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%">
    <el-col :span="24" style="text-align: right;padding-right: 2%">
      <el-select v-model="curType" placeholder="选择类别" size="large" @change="handleSelect" style="width: 20%;">
        <el-option
            v-for="item in typeList"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
    </el-col>
  </el-row>
  <div style="margin-top: 2vh" v-loading="isLoading">
    <el-table :data="tableData(curGoodsList)"
              height="70vh"
              style="width: 100%;"
              :header-cell-style="{ background: '#f6f6f6',  }"

    >
      <el-table-column label="商品名称" width="300">
        <template #default="scope">
          <el-row align='middle'>
            <el-col span="5">
              <el-image :src="scope.row.image" style="height: 70px;">
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </el-col>
            <el-col span="19" style="padding-left: 5%;">
              <el-row style="max-width: 145px"><el-text>{{ scope.row.goodsName }}</el-text></el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="storeSalesNum" label="有售门店数"/>
      <el-table-column label="有售门店比例">
        <template #default="scope">
          {{(scope.row.storeSalesRate * 100).toFixed(0)}}%
        </template>
      </el-table-column>
      <el-table-column prop="avgGross" label="平均毛利"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="warning" round @click="showAdd(scope.row)">进货</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="justify-content: center;align-items:center;height: 60px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
      <div style="flex: 4;" >
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            layout="->,prev, pager, next, jumper"
            :total="curGoodsList.length"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <el-dialog v-model="isShowAdd" title="进货" width="20%">
    <div style="margin-bottom: 10%">
      <div><el-text size="large">{{dataTemp.goodsName}}</el-text></div>
      <div><el-text size="small">{{dataTemp.code}}</el-text></div>
    </div>
    <el-form :model="dataTemp" label-width="70px">
      <el-form-item label="进货数量" prop="num">
        <el-input-number v-model="dataTemp.num" :min="1" style="width: 60%"/>
      </el-form-item>
      <el-form-item label="总价(元)" >
        <el-text>{{dataTemp.num*dataTemp.cost}}</el-text>
      </el-form-item>
    </el-form>
    <div>
      <el-button round size="large" type="warning" style="width: 100px;margin-left: 12%" @click="inPurchase">
        确认
      </el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="showAddNew" title="新增商品"  width="30%" center>
    <el-form :model="goodsStore" :rules="rules" ref="dom" label-width="120px">
      <el-form-item label="商品条码" prop="code">
        <el-input v-model="goodsStore.code" style=" max-width: 250px;"/>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="goodsStore.goodsName" style=" max-width: 250px;"/>
      </el-form-item>
      <el-form-item label="零售价" prop="price">
        <el-input v-model="goodsStore.price" style=" max-width: 100px;"/>
        <el-button style="margin-left: 5%" type="primary" plain @click="getSuggestedPrice">建议价</el-button>
      </el-form-item>
      <el-form-item label="成本价" >
        <el-input v-model="goodsStore.cost" style=" max-width: 100px;"/>
      </el-form-item>
      <el-form-item label="初始库存" >
        <el-input v-model="goodsStore.inventory" style=" max-width: 100px;"/>
      </el-form-item>
      <el-form-item label="自定义库存预警" >
        <el-input v-model="goodsStore.warn" style=" max-width: 100px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addGoodsShow = false">取消</el-button>
        <el-button type="primary" @click="submit(dom)">
          新增
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {store} from "@/store";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";

const typeList=ref([])
let curType=ref("全部商品")
let curGoodsList=ref([])
const goodsList=ref([])
const currentPage = ref(1)
const pageSize = ref(15)
const dataTemp=ref({})
const isShowAdd=ref(false)
let showAddNew=ref(false)
let isLoading=ref(false)
onMounted(()=>{
  isLoading.value=true
  request.get("/business/get/BusinessBigDataSelection").then(res=>{
    console.log(res.data)
    goodsList.value=res.data.businessBigDataSelectionBoList.sort(function (a, b) {
      return b.storeSalesRate-a.storeSalesRate
    })
    curGoodsList.value=goodsList.value
    for (let i in goodsList.value){
      if (typeList.value.indexOf(goodsList.value[i].goodsType)===-1)
        typeList.value.push(goodsList.value[i].goodsType)
    }
    typeList.value.unshift("全部商品")
    isLoading.value=false
  })
})
const handleSelect = (key) => {
  curType.value=key
  curGoodsList.value=filList(key,goodsList.value)
}
const filList = (key,list) => {
  if (key==="全部商品")
    key=""
  // 返回过滤后的数组
  return list.filter((p)=>{
    return p.goodsType.indexOf(key) !==-1
  })
}
const tableData = (list) => {
  return list.filter(
      (item, index) =>
          index < currentPage.value * pageSize.value &&
          index >= pageSize.value * (currentPage.value - 1)
  );
};
const handleCurrentChange = (e) => {
  currentPage.value = e;
};
const showAdd = (data) => {
  if (store.getLocalStorage(data.code)==null){
    addGoods(data)
  }else {
    dataTemp.value=store.getLocalStorage(data.code)
    dataTemp.value.num=1
    isShowAdd.value=true
  }

}
const inPurchase = () => {
  isShowAdd.value=false
  request.get("/goods/get/goodsPurchase/"+store.getLocalCurrentStoreMain().storeId+"?isDone=0").then(res=>{
    if (res.data.length===0){
      let goodsPurchase={
        name:Date.now(),
        storeId:store.getLocalCurrentStoreMain().storeId,
        orderDetailObject:[dataTemp.value],
      }

      request.post("/goods/add/goodsPurchase",goodsPurchase).then(res=>{
        ElMessage({
          message: '已新增进货单',
          type: 'success',
        })
      })
    }else {
      let Temp=[dataTemp.value]
      for (let item in Temp){
        if (res.data[0].orderDetailObject.filter((p)=>{return p.code.indexOf(Temp[item].code) !==-1}).length!==0){
          res.data[0].orderDetailObject[res.data[0].orderDetailObject.indexOf(res.data[0].orderDetailObject.filter((p)=>{
            return p.code.indexOf(Temp[item].code) !==-1})[0])]=Temp[item]
        }else {
          res.data[0].orderDetailObject.push(Temp[item])
        }
      }
      request.post("/goods/update/goodsPurchase",res.data[0]).then(res=>{
        ElMessage({
          message: '已将选中商品加入进货单',
          type: 'success',
        })
      })
    }
  })
}
const addGoods = (data) => {
  goodsStore.code=data.code
  goodsStore.goodsName=data.goodsName
  showAddNew.value=true
}
const goodsStore=reactive({
  code:"",
  goodsName:"",
  storeId:store.getLocalCurrentStoreMain().storeId,
  inventory:0,
  cost:0.0,
  price:0.0,
  warn:3
})
let addGoodsShow=ref(false)
const dom = ref()
const validateCode = (rule, value) => {
  if (value.length !== 13)
    return Promise.reject("请输入正确的13位条形码")
  else
    return Promise.resolve()

}
const validatePrice = (rule, value) => {
  if (value<=0)
    return Promise.reject("价格必须大于0")
  else
    return Promise.resolve()

}
const rules = reactive({
  code:[{validator: validateCode, trigger: 'change',required:true}],
  price:[{validator: validatePrice, trigger: 'change',required:true}]
})

const getSuggestedPrice = () => {
  if (goodsStore.code.length!==13){
    ElMessage({
      message: "请输入正确的商品条码",
      type: 'warning',
    })
  }else {
    request.get("/goods/get/suggestedPrice/"+goodsStore.code).then(res=>{
      if (res.data!==null)
        goodsStore.price=res.data
      else
        ElMessage({
          message: "没有此商品的建议价",
          type: 'warning',
        })
    })
  }
}
const submit = (dom) => {
  dom.validate((isTrue) => {
    if (isTrue) {
      request.post("/goods/add/goodsStore", [goodsStore]).then(response => {
        if (response.code === 200) {
          showAddNew.value=false
          ElMessage({
            message: "已新增商品",
            type: 'success',
          })
          request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res1=>{
            for (let i in res1.data){
              localStorage.removeItem(res1.data[i])
            }
            request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res2=>{
              for (let i in res2.data){
                store.setLocalStorage(res2.data[i].code,res2.data[i])
              }
              store.resetStoreGoodsInfo()
              console.log("resetLocalGoodsInfo done")
              store.goodsStoreInfoList=[]
              for (let i in res1.data){
                store.goodsStoreInfoList.push(store.getLocalStorage(res1.data[i]))
              }
            })
          })
        } else {
          console.log(response)
          ElMessage({
            message: response.message,
            type:'error'
          })
        }
      })
    } else {
      console.log("格式有误")
    }
  })
}
</script>

<style scoped>

</style>